//
//  HomeViewController.swift
//  KCSwift
//
//  Created by apple on 2023/7/21.
//

import UIKit
//import CocoaAsyncSocket
//import SwiftyRSA
import AdSupport
import AppTrackingTransparency
//import Reachability
import Security

//var reachability: Reachability?

class HomeViewController: UIViewController {
    
//    var socket: GCDAsyncSocket?
    let host:String = "216.83.53.19"
    let port = 8001
//    var idfa = "idfa";
    var sqwywi = "16907978706967"
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        checkNetworkState()
//        IDFA()
        
        
        let alertController = UIAlertController(title: "提示", message: "测试dylib", preferredStyle: .alert)
        
        let okAction = UIAlertAction(title: "确定", style: .default) { (_) in
            // 处理 OK 按钮的操作，可以使用传入的参数
           
        }
        
        alertController.addAction(okAction)
        
        // 添加其他操作按钮
        
        // 显示 alert
        if let viewController = UIApplication.shared.keyWindow?.rootViewController {
            viewController.present(alertController, animated: true, completion: nil)
        }
        
        
        print("UUID:",UUID)
        print("Bundle Identifier: \(bundleIdentifier)")
        if let filePath = Bundle.main.path(forResource: "lzh", ofType: nil) {
            do {
                let sign_id = try String(contentsOfFile: filePath)
                self.sqwywi = sign_id
                print("sing-----",sign_id)
            } catch {
                print("Error reading file: \(error)")
            }
        }
        
    }
    // 连接
//    func connectSocket(){
//        socket?.delegate = self
//        socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
//        do {
//            try socket?.connect(toHost: host, onPort: UInt16(port))
//                print("连接成功")
//            sendMessage()
//            }catch _ {
//                print("连接失败")
//
//            }
//    }
    //断开
//    func disconnect(){
//        socket?.disconnect()
//        print("断开成功")
//    }
    
    //发送
//    func sendMessage(){
//        print("sendMessage")
//        let randomStr = randomString(length: 10)
//
//        let parameterDict: [String: String] = ["cmd": "verify", "app_request_id": randomStr, "sqwywi": sqwywi,"aiyhsg":"cn.com.icbc.bizElife.ICBCNotificationService","iytgkse":UUID]
//        if let jsonString = dictionaryToJsonString(dictionary: parameterDict) {
//            print("JSON string: \(jsonString)")
//            //rsa加密
//            let rsaEncrypt = rsa_encrypt(jsonString)
//            print("rsa加密结果----",rsaEncrypt)
//            //base64加密
//            if let encodedString = Base64Utility.encodeString(rsaEncrypt) {
//                print("base64加密结果===: \(encodedString)")
//                if let data = stringToData(string: encodedString) {
//                    socket?.write(data, withTimeout: -1, tag: 0)
//                }
//            } else {
//                print("base64加密失败")
//            }
//        }else{
//            print("转json字符串失败")
//        }
//    }
//
    // 随机数
    func randomString(length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
    // 字典转data
//    func convertDictionaryToData<T: Encodable>(dictionary: [String: T]) -> Data? {
//        do {
//            let jsonData = try JSONEncoder().encode(dictionary)
//            return jsonData
//        } catch {
//            print("Error encoding dictionary to data: \(error)")
//            return nil
//        }
//    }
    // 字典转json字符串
    func dictionaryToJsonString(dictionary: [String: Any]) -> String? {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: [])
            let jsonString = String(data: jsonData, encoding: .utf8)
            return jsonString
        } catch {
            print("Error converting dictionary to JSON string: \(error)")
            return nil
        }
    }
    // 字符串转data
    func stringToData(string: String) -> Data? {
        if let data = string.data(using: .utf8) {
            return data
        } else {
            print("Error converting string to data")
            return nil
        }
    }
    
    // 读取文件
    func readFileContent(atPath path: String) -> String? {
        let fileURL = URL(fileURLWithPath: path)
        
        do {
            let fileData = try Data(contentsOf: fileURL)
            if let fileContent = String(data: fileData, encoding: .utf8) {
            print("fill====",fileContent)
                return fileContent
            }
        } catch {
            print("Error reading file: \(error)")
        }
        
        return nil
    }
    
//    func checkNetworkState() {
//       reachability = try! Reachability()
//       reachability?.whenReachable = { reach in
//           switch reach.connection {
//           case .wifi:
//               print("Reachable via WiFi")
//               self.connectSocket()
//           case .cellular:
//               print("Reachable via Cellular")
//               self.connectSocket()
//           case .unavailable, .none:
//               fallthrough
//           default:
//               print("Network not reachable")
//           }
//       }
//       reachability?.whenUnreachable = { _ in
//           print("Not reachable")
//       }
//
//       do {
//           try reachability?.startNotifier()
//       } catch {
//           print("Unable to start notifier")
//       }
//   }
    
}


//extension HomeViewController:GCDAsyncSocketDelegate{
//    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) -> Void {
//        print("\n已连接： \nhost:\(host) \nport:\(port)" )
//
//    }
//
//    // 读取服务器发来的数据
//    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
//        // 对data进行处理
//        let str=String(data:data,encoding:.utf8)!
//        //base64解密
//        if let decodedString = Base64Utility.decodeString(str) {
//            print("Decoded string: \(decodedString)")
//            //rsa解密
//            let pri = rsa_decrypt(decodedString)
//            print("后端返回结果===",pri)
//
//            if let dictionary  = jsonStringToDictionary(jsonString: pri) {
//                print("Dictionary: \(dictionary)")
//                if let chgfox = dictionary["chgfox"] as? String {
//                    print("chgfox: \(chgfox)")
//
//                    if chgfox == "isdoei"{
//                        print("其他异常闪退")
//                        exit(0)
//                    }else if chgfox == "osufeewttte"{
//                        print("闪退")
////                        exit(0)
//                    }else if chgfox == "jdffdewasgw"{
//                        print("弹框")
//                        if let meygsw = dictionary["meygsw"] as? String {
//                            showAlert2(withMessage: meygsw)
//                        }
//                    }else if chgfox == "odktrtewgor"{
//                        print("弹框+确定")
//                        if let meygsw = dictionary["meygsw"] as? String {
//                            showAlert(withMessage: meygsw)
//                        }
//                    }
//
//
//                }
//            }
//
//        } else {
//            print("base64解密失败")
//        }
//    }
//
//    // 每次写入成功后，sock需要执行一次readData
//    func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
//        sock.readData(withTimeout: -1, tag: 0)
//    }
//    // 断开连接
//    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
//        print("\n已断开连接")
//    }
//
//
//}


func showAlert(withMessage message: String) {
    let alertController = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
    
    let okAction = UIAlertAction(title: "确定", style: .default) { (_) in
        // 处理 OK 按钮的操作，可以使用传入的参数
        print("OK button tapped with message: \(message)")
    }
    
    alertController.addAction(okAction)
    
    // 添加其他操作按钮
    
    // 显示 alert
    if let viewController = UIApplication.shared.keyWindow?.rootViewController {
        viewController.present(alertController, animated: true, completion: nil)
    }
}

func showAlert2(withMessage message: String) {
    let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert)
    // 显示 alert
    if let viewController = UIApplication.shared.keyWindow?.rootViewController {
        viewController.present(alertController, animated: true, completion: nil)
    }
}

func dataToJSONString(data: Data) -> String? {
    do {
        let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
        let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            return jsonString
        }
    } catch {
        print("Failed to convert data to JSON string: \(error)")
    }
    return nil
}
// 字符串转字典
func jsonStringToDictionary(jsonString: String) -> [String: Any]? {
    if let jsonData = jsonString.data(using: .utf8) {
        do {
            if let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                return dictionary
            }
        } catch {
            print("Error converting JSON string to dictionary: \(error)")
        }
    }
    
    return nil
}


///rsa加密
// func rsa_encrypt(_ str:String) -> String{
//    var reslutStr = ""
//    do{
//        let pub = "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAoGZ84kmJYGAmGmbJ8lBKWzawjoZtKT4IXaLkUE0K4yYTd+odxVJJcD/CPmlsQTBRtZlITPt505uiAexoSDaJbfMqRZuRbrZFBilFK//s3C7Z+HB8I6pa51G5rQ/YZxM61FmIJ0ZhCVPLi9GwRIf+YJ0I25tCZvIAaJP+rZM+Qff+xUjHmcx87CpLWmyhtc23pTLvxYgYkssiV7f+Rl5oD3B2HcEZTaIH709bkyqgyLldo3TX72PLzoa91EBpJ3e/28Ga5Vbcb+lOF3Ss6kJZANv4jSMtxz86OUQAlwxj5+4Kf8mPH7HSe6gnk1p+Uoi4iP7DLsj2rIyX3vCagPWlQCY35MpAoPWEHHnJk7b2t1RoUpF6gMRpA8HqtjK8QGkbWKS1AIQvJm/Uo6HhePigUZMhRW1xhI/qkgpvI+CUl5Ndz9qYtS473MT/T/wagrslP2dctW1oyWK32ZaiCVtWrOarkYGgy57kemyPLR2mP2RxPiFrMaxyhbynLJT+fg4XCFvkaXf/0dwIdIoOd0HES41sm5zQ8XIGDfa2ipjTxwAszBws4yrDDrQiCWoXcIOWJ1dlAJQjmXgVCS7+Nd8hqxh8N8PAwk1U+nwBiOw2ulB/3spQEBMHcjKO2sxeCvesE9HjNG8r59OimEnzsfZx67WJVCCCvres+P6de6r9DSkCAwEAAQ=="
//        let rsa_publicKey = try PublicKey(pemEncoded: pub)
//        let clear = try ClearMessage(string: str, using: .utf8)
//        reslutStr = try clear.encrypted(with: rsa_publicKey, padding: .PKCS1).base64String
//
//    }catch{
//        print("RSA加密失败")
//    }
//    return reslutStr;
//}
//
//
//func rsa_decrypt(_ str: String) -> String {
//    var resultStr = ""
//    let enData = Data(base64Encoded: str, options: .ignoreUnknownCharacters)!
//    do {
//        let pri = "MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCeq7OoJP/pkK0ThwnebeQlEIbnvUbLZZ52hci1SElOYzsTa4Fi+CShIm4bHhX56hBc7aUazPPvIGvSLFUisdCwrasIgtKhIOJZKXF8NokMHpxGy5SOQHrQRVn55M1mZhyCw59feYK7pDlzDF4UMAPr2QJwTpMQyj3AnFYM2LiN8NQsjOAOOgP+DuHtXBMZON2MZWX1HC/aLvBaybaBF13w/JRrcbTu2a8h4T0Kpdj8skZ9MDrK+sBRyiR4s+Ejl0v/IbYgoxb3n68q7IOYOA8dpJ1PIdMPSoEu0FB9tX7BCj+xamwUkdUrANkxtNZKskdK1XxXE/HB0YIjhLs14Ixf1hr+aLjoyRCraybtmP13L9BdvX4CHYcKTay6q/DOSaF1jlzfa9ztSH+9xHFZ/tiX/1x1pkkAvhKlXdffY8pUlGUYDtbNjI04r75xXBj364t93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VyXQPmeL6IEwKcV4pMcfW1hjJ7dZyAjO+BRGxLQ+tx8Duj5UOhcpZIdbo3RU4pS0SlqpAuVsxrrT+QUMPYYrk40bORbHPYS4WI4sj7+dzbotruzvT1ENUEuIMfheWpOnm64Xj8oEwkM75AECggEAPTbJqk1S1YYT54hUnk4Ii/qF7FNuXUNPvnQDvD6rdVeMvEKYtVIVsrkZg00V1xOVZjgWkl/Iv7AvCiG9Ve/rBEimLbzrUfg98jlGBoNyr5KUuXPS70MxeA2zQnBN3vSPaioPXh1+QxbCmjxK9WCRVaKKosLnDkXX3ZWPfC6EcbyvqqRtlQvidsuJJ7F1kJrgHBcb3K1i+UhV3O4pnnumKj1KTv82yu/0Igj21K7r7cgm9zHPO/j/Wr2kVwK+v4h9UzONde9+TXyLbGAb1NkDD4gF8kfCDMoSUrVZsjHNTkzmXLryqvlmzf5SLjqx5fnWZ16ioAf705VHZD6YLtzeTw=="
//        let rsa_privateKey = try PrivateKey(pemEncoded: pri)
//
//        let decryptedData = try EncryptedMessage(data: enData).decrypted(with: rsa_privateKey, padding: .PKCS1).data
//
//        decryptedData.withUnsafeBytes { rawBufferPointer in
//            let data = Data(rawBufferPointer)
//            resultStr = String(data: data, encoding: .utf8) ?? ""
//        }
//    } catch {
//        print("RSA decryption failed: \(error)")
//    }
//    return resultStr
//}

 //获取UUID
class KeychainItemWrapper {
    let identifier: String
    let accessGroup: String?
    
    init(identifier: String, accessGroup: String?) {
        self.identifier = identifier
        self.accessGroup = accessGroup
    }
    
    func objectForKey(_ key: AnyObject) -> String? {
        var result: AnyObject?
        
        let query = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: identifier,
            kSecReturnData: kCFBooleanTrue!,
            kSecMatchLimit: kSecMatchLimitOne
        ] as CFDictionary
        
        let status = SecItemCopyMatching(query, &result)
        
        guard status == errSecSuccess,
              let data = result as? Data,
              let value = String(data: data, encoding: .utf8)
        else {
            return nil
        }
        
        return value
    }
    
    func setObject(_ object: String?, forKey key: AnyObject) {
        guard let object = object else {
            return
        }
        
        let encodedObject = object.data(using: .utf8)!
        
        let query = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: identifier,
            kSecValueData: encodedObject
        ] as CFDictionary
        
        SecItemDelete(query)
        SecItemAdd(query, nil)
    }
}

func getUUID() -> String {
    let keyChainWrapper = KeychainItemWrapper(identifier: "MYAppID", accessGroup: "com.test.app")
    if let UUID = keyChainWrapper.objectForKey(kSecValueData as AnyObject),
       !UUID.isEmpty {
        return UUID
    }
    
    let UUID = UIDevice.current.identifierForVendor?.uuidString ?? ""
    keyChainWrapper.setObject(UUID, forKey: kSecValueData as AnyObject)
    
    return UUID
}

let UUID = getUUID()

//获取plist
extension Bundle {
    static var appBundleIdentifier: String {
        return main.bundleIdentifier ?? ""
    }
}
let bundleIdentifier = Bundle.appBundleIdentifier
